#!/usr/bin/env python

from time import time
from tqdm import tqdm
from wt.db.redis.pika import PIKA
from wt.db.pg import PG
from random import shuffle


def table_iter_for_update(table_iter, where={}, duration=86400, next_time=None):
    key = table_iter._key

    if int(table_iter._begin_id) == 0:
        PIKA.delete(key)

    for i in table_iter(where):
        # print(i)
        PIKA.zadd(key, 0, i.id)
    now = int(time())
    # print(key)
    li = PIKA.zrangebyscore(key, 0, now)
    # shuffle(li)

    if next_time is None:

        def next_time(o):
            return now + duration

    for id in tqdm(li, unit="row"):
        o = PG.select_one(table_iter._table, dict(id=id))
        yield o
        PIKA.zadd(key, next_time(o), id)


if __name__ == "__main__":
    main()
